/**
 * Created by FreezeSoul on 2016/3/29.
 */
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "raphael",
    "underscore",
    'JSONParse',
    'loglevel',
    'jqueryTmpl',
    'jQueryUUID'
], function (Chart, Util, Meta, $, Raphael, _, JSON, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'BeiJingSe',
                name: '背景色',
                enable: false,
                type: 'color',
                value: '#101a10',
                default: '#101a10',
                link: 'backColor',
                tooltip: '背景色'
            },
            {
                group: '基础',
                id: 'QianJingSe',
                name: '前景色',
                enable: false,
                type: 'color',
                value: '#aaff00',
                default: '#aaff00',
                link: 'fontColor',
                tooltip: '前景色'
            },
            {
                group: '基础',
                id: 'DaXiao',
                name: '尺寸',
                enable: false,
                type: 'number',
                value: 20,
                default: 20,
                link: 'size',
                tooltip: '尺寸'
            },
            {
                group: '基础',
                id: 'TextAlign',
                name: '对齐方式',
                enable: false,
                type: 'select',
                value: 'left',
                default: 'left',
                data: [{
                    value: 'left',
                    text: 'left'
                }, {
                    value: 'right',
                    text: 'right'
                }, {
                    value: 'center',
                    text: 'center'
                }],
                link: 'textAlign',
                tooltip: '字体对齐方式'
            },
            {
                group: '基础',
                id: 'ChangDu',
                name: '长度',
                enable: false,
                type: 'number',
                value: 0,
                default: 0,
                link: 'length',
                tooltip: '长度,“0”表示按数字长度自动缩放'
            },
            {
                group: '基础',
                id: 'YuanJiao',
                name: '圆角',
                enable: false,
                type: 'number',
                value: 5,
                default: 5,
                link: 'rounded',
                tooltip: '圆角'
            },
            {
                group: '基础',
                id: 'ZiTi',
                name: '字体',
                enable: false,
                type: 'select',
                value: '0',
                default: '0',
                data: [
                    {
                        value: '0',
                        text: '字体1'
                    },
                    {
                        value: '1',
                        text: '字体2'
                    },
                    {
                        value: '2',
                        text: '字体3'
                    }
                ],
                link: 'fontStyle',
                tooltip: '字体风格'
            },
            {
                group: '基础',
                id: 'ShuZhi',
                name: '初始值',
                enable: false,
                type: 'number',
                value: 0,
                default: 0,
                link: 'numeric',
                tooltip: '初始值'
            },
            {
                group: '基础',
                id: 'HoverAnimationList',
                name: '鼠标响应',
                enable: false,
                type: 'select',
                value: '',
                default: '',
                data: [{
                    value: '',
                    text: '无效果'
                }, {value: 'bounce', text: 'bounce'},
                    {value: 'flash', text: 'flash'},
                    {value: 'pulse', text: 'pulse'},
                    {value: 'rubberBand', text: 'rubberBand'},
                    {value: 'shake', text: 'shake'},
                    {value: 'headShake', text: 'headShake'},
                    {value: 'swing', text: 'swing'},
                    {value: 'tada', text: 'tada'},
                    {value: 'wobble', text: 'wobble'},
                    {value: 'jello', text: 'jello'},
                    {value: 'bounceIn', text: 'bounceIn'},
                    {value: 'bounceInDown', text: 'bounceInDown'},
                    {value: 'bounceInLeft', text: 'bounceInLeft'},
                    {value: 'bounceInRight', text: 'bounceInRight'},
                    {value: 'bounceInUp', text: 'bounceInUp'},
                    {value: 'bounceOut', text: 'bounceOut'},
                    {value: 'bounceOutDown', text: 'bounceOutDown'},
                    {value: 'bounceOutLeft', text: 'bounceOutLeft'},
                    {value: 'bounceOutRight', text: 'bounceOutRight'},
                    {value: 'bounceOutUp', text: 'bounceOutUp'},
                    {value: 'fadeIn', text: 'fadeIn'},
                    {value: 'fadeInDown', text: 'fadeInDown'},
                    {value: 'fadeInDownBig', text: 'fadeInDownBig'},
                    {value: 'fadeInLeft', text: 'fadeInLeft'},
                    {value: 'fadeInLeftBig', text: 'fadeInLeftBig'},
                    {value: 'fadeInRight', text: 'fadeInRight'},
                    {value: 'fadeInRightBig', text: 'fadeInRightBig'},
                    {value: 'fadeInUp', text: 'fadeInUp'},
                    {value: 'fadeInUpBig', text: 'fadeInUpBig'},
                    {value: 'fadeOut', text: 'fadeOut'},
                    {value: 'fadeOutDown', text: 'fadeOutDown'},
                    {value: 'fadeOutDownBig', text: 'fadeOutDownBig'},
                    {value: 'fadeOutLeft', text: 'fadeOutLeft'},
                    {value: 'fadeOutLeftBig', text: 'fadeOutLeftBig'},
                    {value: 'fadeOutRight', text: 'fadeOutRight'},
                    {value: 'fadeOutRightBig', text: 'fadeOutRightBig'},
                    {value: 'fadeOutUp', text: 'fadeOutUp'},
                    {value: 'fadeOutUpBig', text: 'fadeOutUpBig'},
                    {value: 'flipInX', text: 'flipInX'},
                    {value: 'flipInY', text: 'flipInY'},
                    {value: 'flipOutX', text: 'flipOutX'},
                    {value: 'flipOutY', text: 'flipOutY'},
                    {value: 'lightSpeedIn', text: 'lightSpeedIn'},
                    {value: 'lightSpeedOut', text: 'lightSpeedOut'},
                    {value: 'rotateIn', text: 'rotateIn'},
                    {value: 'rotateInDownLeft', text: 'rotateInDownLeft'},
                    {value: 'rotateInDownRight', text: 'rotateInDownRight'},
                    {value: 'rotateInUpLeft', text: 'rotateInUpLeft'},
                    {value: 'rotateInUpRight', text: 'rotateInUpRight'},
                    {value: 'rotateOut', text: 'rotateOut'},
                    {value: 'rotateOutDownLeft', text: 'rotateOutDownLeft'},
                    {value: 'rotateOutDownRight', text: 'rotateOutDownRight'},
                    {value: 'rotateOutUpLeft', text: 'rotateOutUpLeft'},
                    {value: 'rotateOutUpRight', text: 'rotateOutUpRight'},
                    {value: 'hinge', text: 'hinge'},
                    {value: 'jackInTheBox', text: 'jackInTheBox'},
                    {value: 'rollIn', text: 'rollIn'},
                    {value: 'rollOut', text: 'rollOut'},
                    {value: 'zoomIn', text: 'zoomIn'},
                    {value: 'zoomInDown', text: 'zoomInDown'},
                    {value: 'zoomInLeft', text: 'zoomInLeft'},
                    {value: 'zoomInRight', text: 'zoomInRight'},
                    {value: 'zoomInUp', text: 'zoomInUp'},
                    {value: 'zoomOut', text: 'zoomOut'},
                    {value: 'zoomOutDown', text: 'zoomOutDown'},
                    {value: 'zoomOutLeft', text: 'zoomOutLeft'},
                    {value: 'zoomOutRight', text: 'zoomOutRight'},
                    {value: 'zoomOutUp', text: 'zoomOutUp'},
                    {value: 'slideInDown', text: 'slideInDown'},
                    {value: 'slideInLeft', text: 'slideInLeft'},
                    {value: 'slideInRight', text: 'slideInRight'},
                    {value: 'slideInUp', text: 'slideInUp'},
                    {value: 'slideOutDown', text: 'slideOutDown'},
                    {value: 'slideOutLeft', text: 'slideOutLeft'},
                    {value: 'slideOutRight', text: 'slideOutRight'},
                    {value: 'slideOutUp', text: 'slideOutUp'}],
                link: 'hoverAnimation',
                tooltip: '鼠标响应动画'
            },
            {
                group: '绑定',
                id: 'BangDing',
                name: '绑定',
                enable: false,
                type: 'textBinding',
                dataset: '',
                ctype: 'measure',
                column: {},
                tooltip: '数值绑定，请绑定数值字段'
            },
            {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            },
            {
                group: '事件',
                id: 'LabelClick',
                name: '点击跳转事件',
                enable: true,
                type: 'pivotEvent',
                value: {
                    Event: "LabelClick",
                    Params: [
                        {Value: "Text", Name: "文本"}
                    ]
                },
                tooltip: '点击跳转事件，钻取设置'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var led = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._element = null;
            this._lastdata = null;
            this._container = null;
            this._uLEDType = null;
            this._uLEDObj = null;
            this._currentValue = null;
            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    fontColor: "#aaff00",
                    backColor: "#101a10",
                    size: 20,  //尺寸
                    length: 0,  //长度
                    rounded: 5,  //圆角
                    numeric: 999,  //数值
                    fontStyle: "0", //字体
                    textAlign: "left",
                    hoverAnimation: "",
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                var _this = this;
                this._uuid = $.uuid();
                this._container = element;
                var deferred = $.Deferred();
                window.Raphael = Raphael;
                require(['app/plugins/controls/common/ledlabel/resource/jquery.uled'], function (uLED) {
                    _this._uLEDType = uLED;
                    deferred.resolve();
                });
                return deferred.promise();
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function () {
            if (this.__isEditMode) {
                this._uLEDObj = null;
            }
            if (this._option.Option.length === 0
                && String(this._currentValue).length !== this._option.Option.length) {
                this._uLEDObj = null;
            }
            if (this._uLEDObj === null) {
                var $element = $('<div id="LED-Label' + this._uuid + '" style="text-align: ' + this._option.Option.textAlign + ';"></div>');
                $(this._container).empty();
                $element.appendTo(this._container);
                if (this._uLEDType) {
                    if (this._currentValue === null) {
                        this._currentValue = this._option.Option.numeric;
                    }
                    var option = {
                        id: "LED-Label" + this._uuid,
                        type: "numeric",
                        color: this._option.Option.fontColor,
                        bgcolor: this._option.Option.backColor,
                        length: this._option.Option.length,
                        size: this._option.Option.size,
                        rounded: this._option.Option.rounded,
                        font: this._option.Option.fontStyle
                    };
                    if (option.length === 0 && option.length !== String(this._currentValue).length) {
                        option.length = String(this._currentValue).length;
                    }
                    try {
                        this._uLEDObj = new this._uLEDType(option);
                        this._uLEDObj.updateNumeric(this._currentValue);
                    } catch (e) {
                        //log.error(e);
                    }
                }
                this._bindEvent($element);
                if (this._option.Option.hoverAnimation) {
                    var _this = this;
                    $element.hover(
                        function () {
                            if ($element.hasClass("animated")) return;
                            $element.addClass("animated " + _this._option.Option.hoverAnimation)
                                .one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function () {
                                    $element.removeClass("animated " + _this._option.Option.hoverAnimation)
                                });
                        }, function () {
                        }
                    );
                }

                //Util.setCommonMeta(this, this._container, this._option.Option);
                //Util.initChartLifeTime(this, this._container, this._option.Option);

                this._element = $element;
            } else {
                try {
                    this._uLEDObj.updateNumeric(this._currentValue);
                } catch (e) {
                    log.error(e);
                }
            }
        },
        _bindEvent: function (element) {
            var _this = this;
            $(element).on("click", function (e) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "LabelClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Name: "文本"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: _this._currentValue
                            });
                        }
                        _this._layout.navigate(pageId, args);
                    }
                    e.preventDefault();
                }
            });

            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        example: function () {
            try {
                this._render();
            } catch (e) {
                log.error(e);
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        setData: function (data) {
            try {
                this._lastdata = data;

                this._readProperty();
                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    var bindProperty = _.findWhere(this._option.Extend.option, {type: 'textBinding'});
                    if (bindProperty && bindProperty.dataset) {
                        var dataSetCode = bindProperty.dataset;
                        var table = data[dataSetCode];
                        table = this._filterTable(this._option.Extend.option, table);
                        if (table && table.length > 0 && bindProperty.column) {
                            var row = table[0];
                            var columnName = bindProperty.column.ColumnName;
                            if (columnName) {
                                var row_value = row[columnName];
                                if (!isNaN(row_value)) {
                                    this._currentValue = parseFloat(row_value);
                                }
                            }
                        }
                    } else {
                        this._currentValue = this._option.Option.numeric;
                    }
                }
                this._render();
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._element).off().remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._element;
        }
    });

    return {
        Chart: led,
        Property: property
    };
});